import { defineStore } from 'pinia'
import {ref,computed} from 'vue'
export const useCounterStore = defineStore('counter', () => {
  //购物车列表
  const cartList =ref([])

  const myOrderList=ref([])

  //购物车判断
  const addItem=(playload)=>{
    const index = cartList.value.findIndex(item=>item.id==playload.id)
    if(index>-1)
    {
        cartList.value[index].count++
    }else
    {
        cartList.value.push({
            ...playload,
            count:1,
            checked:false
        })
    }
  }

  //删除
  const delItem =(id)=>{
    cartList.value=cartList.value.filter(item=>item.id !=id)
  }

  //总价
  const totalPrice =computed(()=>{
    let res =0;
    cartList.value.forEach(item=>{
      if(item.checked==true)
      {
        res +=item.count*item.price
      }
    })
    return res
  })
  //总数量
  const totalCount =computed(()=>{
      let res =0;
    cartList.value.forEach(item=>{
      
        res +=item.count
      
    })
    return res
  })
   
  const orderList =()=>{
    return orderList.value.filter(item=>item.checked==true)
  }
 const addMyOrder=(payload)=>{
     myOrderList.value.push(payload)
 }
  return {cartList,addItem,delItem ,totalCount,totalPrice,myOrderList,orderList,addMyOrder }
},{
    persist:true
})